# Helper functions ----

#function for getting margins
plotexpmargins <- function(m1,m2,ylab,title){
  mgdf <- margins(m1,variables = "expcondition") %>% 
    summary() %>% 
    bind_rows(summary(margins(m2,variables = "expcondition"))) %>% 
    mutate(model=rep(c("Bivariate","Adjusted"),each=2)) %>% 
    bind_rows(.,tibble(AME=0,SE=0,model="Bivariate")) %>% 
    mutate(cond=fct_relevel(factor(c(rep(c("Accommodative","Adversarial"),2),"Control")),c("Adversarial","Control")),
           model=fct_relevel(model,"Bivariate")) %>% 
    filter(cond!="Control") 
  
  mgplot <- ggplot(data=mgdf,aes(x=cond,y=AME,group=model,color=model)) +
    geom_hline(yintercept = 0,linetype="dotted") +
    geom_point(position = position_dodge(width=.3),size=3) +
    geom_errorbar(aes(ymin=AME-1.65*SE,ymax=AME+1.65*SE),width=0,size=1.2,position = position_dodge(width=.3)) +
    geom_errorbar(aes(ymin=AME-1.96*SE,ymax=AME+1.96*SE),width=0,size=.8,position = position_dodge(width=.3)) +
    theme_bw() +
    labs(x="",y=ylab) +
    ggtitle(title) +
    ylim(c(min(min(mgdf$lower)-.001,-.04),max(max(mgdf$upper)+.001,.12))) +
    scale_color_manual(values=c("black","gray")) +
    theme(legend.position = "none",axis.text.x = element_text(size=12,color = "black"))
  
  return(mgplot)
}

#margins function
getintmarginsdf <- function(model,moderator,refadv,modeltype,comptype){
  if(moderator=="antiimm"){
    varlist <- list(antiimm=seq(0,1,.125))
  }
  if(moderator=="partygroup15"){
    varlist <- list(partygroup15=levels(acdf$partygroup15))
  }
  if(refadv==TRUE){
    mdfx <- margins(model,variables = "expcondition_refadv",at=varlist) %>% 
      summary() %>% 
      filter(factor=="expcondition_refadvAccommodative") %>% 
      mutate(model=modeltype,comp=comptype)
    return(mdfx)
  }
  if(refadv==FALSE){
    mdfx <- margins(model,variables = "expcondition",at=varlist) %>% 
      summary() %>% 
      filter(factor=="expconditionAccommodative") %>% 
      mutate(model=modeltype,comp=comptype)
    return(mdfx)
  }
}

getbalancetests <- function(fctvar,fctvarlab){
  
  indepvar <- select(acdf,starts_with(fctvar)) %>% 
    pull(1)
  
  xmnlogit <- multinom(acdf$expcondition~indepvar)
  
  #  xlm <- lm(depvar ~ acdf$expcondition)
  
  xdf <- broom::tidy(xmnlogit) %>% 
    mutate(var=fctvarlab) %>% 
    mutate(varlab=rep(levels(indepvar),2))
  
  return(xdf)
}